package com.cljz.makepassenger.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.cljz.makepassenger.base.App;
import com.cljz.makepassenger.R;
import com.cljz.makepassenger.base.BaseActivity;
import com.cljz.makepassenger.model.net.bean.GetCityBean;
import com.cljz.makepassenger.model.map.City;
import com.cljz.makepassenger.model.map.Province;
import com.cljz.makepassenger.present.activity.CityListP;
import com.cljz.makepassenger.service.LocationService;
import com.cljz.makepassenger.ui.adapter.CityListAdapter;
import com.cljz.makepassenger.ui.adapter.base.HeaderRecyclerAndFooterWrapperAdapter;
import com.cljz.makepassenger.ui.holder.base.ViewHolder;
import com.cljz.makepassenger.utils.L;
import com.cljz.makepassenger.widget.indexbar.IndexBar.widget.IndexBar;
import com.cljz.makepassenger.widget.indexbar.suspension.SuspensionDecoration;
import com.google.gson.Gson;
import com.jakewharton.rxbinding.view.RxView;

import org.json.JSONArray;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.router.Router;
import rx.functions.Action1;

/**
 * Created by apple on 2017/4/7.
 */

public class CityListActivity extends BaseActivity<CityListP> implements OnGetGeoCoderResultListener, BDLocationListener {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.fl_back)
    FrameLayout flBack;
    @BindView(R.id.tv_title_name)
    TextView tvTitleName;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.rv_city_list)
    RecyclerView rvCityList;
    @BindView(R.id.ib_index)
    IndexBar ibIndex;
    @BindView(R.id.tv_show_index)
    TextView tvShowIndex;
    @BindView(R.id.rl_city_list_main)
    RelativeLayout rlCityListMain;

    private GeoCoder mSearch;
    private List<City> cityList;
    private ArrayList<Province> provinces = new ArrayList<>();
    private SuspensionDecoration mDecoration;
    private City mCity;
    private LocationService locationService;
    private CityListAdapter cityListAdapter;
    private HeaderRecyclerAndFooterWrapperAdapter mHeaderAdapter;


    @Override
    public void initData(Bundle savedInstanceState) {
        ivBack.setImageDrawable(getResources().getDrawable(R.mipmap.icon_close));
        tvTitleName.setText("选择城市");
        locationService = App.getLocationService();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        rvCityList.setLayoutManager(linearLayoutManager);
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);
        cityListAdapter = new CityListAdapter(this, cityList, new CityListAdapter.CityCallBack() {
            @Override
            public void OnItemClick(City city) {
                mCity = city;
                mSearch.geocode(new GeoCodeOption()
                        .city(city.getAreaName()).address(city.getAreaName()));

            }
        });

        mHeaderAdapter = new HeaderRecyclerAndFooterWrapperAdapter(cityListAdapter) {
            @Override
            protected void onBindHeaderHolder(ViewHolder holder, int headerPos, int layoutId, Object o) {
                holder.setText(R.id.tv_local_city, (String) o);
            }
        };
        mHeaderAdapter.setHeaderView(R.layout.item_header_city_list, getIntent().getExtras().getString("city"));
        rvCityList.setAdapter(mHeaderAdapter);
        rvCityList.addItemDecoration(mDecoration = new SuspensionDecoration(this, cityList).setHeaderViewCount(mHeaderAdapter.getHeaderViewCount()));
        ibIndex.setmPressedShowTextView(tvShowIndex)//设置HintTextView
                .setNeedRealIndex(true)//设置需要真实的索引
                .setmLayoutManager(linearLayoutManager);//设置RecyclerView的LayoutManager
        cityList = new ArrayList<>();
        new InitAreaTask(this).execute(0);

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_city_list;
    }

    @Override
    public CityListP newP() {
        return new CityListP();
    }


    @Override
    protected void initListener() {
        super.initListener();
        RxView.clicks(flBack)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                Router.pop(CityListActivity.this);
            }
        });
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
        if (geoCodeResult == null || geoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            //没有检索到结果
        } else {
            mCity.setAddress(geoCodeResult.getAddress());
            mCity.setLatitude(geoCodeResult.getLocation().latitude);
            mCity.setLongitude(geoCodeResult.getLocation().longitude);
            Intent intent = new Intent();
            intent.putExtra("data", mCity);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {

    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
//        getP().getCity(bdLocation.getProvince(), bdLocation.getCity());
        L.e(bdLocation.getCity());
    }



    public void getCitySucceed(GetCityBean getCityBean) {
        mCity.setCity_id(getCityBean.getData().getCity_id());
    }

    public void getCityFail(String msg) {

    }

    /*／初始化地址数据*/
    private class InitAreaTask extends AsyncTask<Integer, Integer, Boolean> {
        Context mContext;


        public InitAreaTask(Context context) {
            mContext = context;

        }

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected void onPostExecute(Boolean result) {
            for (int i = 0; i < provinces.size(); i++) {
                for (int j = 0; j < provinces.get(i).getCities().size(); j++) {
                    provinces.get(i).getCities().get(j).setProvice(provinces.get(i).getAreaName());
                    provinces.get(i).getCities().get(j).setCityName(provinces.get(i).getCities().get(j).getAreaName());
                    cityList.add(provinces.get(i).getCities().get(j));
                }
            }
            ibIndex.setmSourceDatas(cityList)//设置数据
                    .setHeaderViewCount(mHeaderAdapter.getHeaderViewCount())//设置HeaderView数量
                    .invalidate();

            cityListAdapter.setDatas(cityList);
            mHeaderAdapter.notifyDataSetChanged();
            mDecoration.setmDatas(cityList);
        }

        @Override
        protected Boolean doInBackground(Integer... params) {
            String address = null;
            InputStream in = null;
            try {
                in = mContext.getResources().getAssets().open("address.txt");
                byte[] arrayOfByte = new byte[in.available()];
                in.read(arrayOfByte);
                address = new String(arrayOfByte, "UTF-8");
                JSONArray jsonList = new JSONArray(address);
                Gson gson = new Gson();
                for (int i = 0; i < jsonList.length(); i++) {

                    provinces.add(gson.fromJson(jsonList.getString(i),
                            Province.class));

                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return false;
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        locationService.registerListener(this);
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        locationService.start();// 定位SDK
    }

    @Override
    protected void onStop() {
        super.onStop();
        locationService.unregisterListener(this);
        locationService.stop();
    }
}
